package com.meeting.manager.net;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class VolleySingleton {
    private static VolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;
 
    private VolleySingleton(Context context) {
        mCtx = context.getApplicationContext();
        mRequestQueue = getRequestQueue();
 
        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap>
                    cache = new LruCache<String, Bitmap>((int) Runtime.getRuntime().maxMemory()/8){

						@Override
						protected int sizeOf(String key, Bitmap value) {
							
							return value.getRowBytes()*value.getHeight();
						}
            	
            };
 
            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }
 
            @Override
            public void putBitmap(String url, Bitmap bitmap) {
            	if(url == null)return;
            	if(bitmap == null)return;
            	if(getBitmap(url) == null){
            		cache.put(url, bitmap);
            	}
            }
        });
    }
 
    public static synchronized VolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleySingleton(context.getApplicationContext());
        }
        return mInstance;
    }
 
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }
 
    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }
 
    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}